<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;

class UserSessionIsValid
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! auth()->check()) {
            return redirect()->route('login')->withErrors([
                'errors' => '您需要先登录才能访问该页面。',
            ]);
        }

        $user = $request->user();

        if (! $user->isActive()) {
            return redirect()->route('login')->withErrors([
                'errors' => '您的账号已被禁用，请联系管理员。',
            ]);
        }

        if (! $user->hasRole('merchant')) {
            return redirect()->route('index')->withErrors([
                'errors' => '您不是商家账号，无法访问该页面。',
            ]);
        }

        Inertia::share([
            'auth' => [
                'name' => $user->name,
                'avatar' => $user->avatar ?? '/static/images/avatar.jpg',
                'email' => $user->email,
            ],
        ]);

        return $next($request);
    }
}
